package com.wencst.security.handler;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.Map;

import org.apache.commons.io.FileUtils;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.util.ResourceUtils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.wencst.security.bean.User;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@Service
public class UserService {
	
	public User getUserByName(String username) {
		User user = null;
		try {
			user = getUserInFile("classpath:templates/json/users.json",username);
		} catch (UsernameNotFoundException e) {
			try {
				user = getUserInFile("classpath:json/users.json",username);
			}catch (UsernameNotFoundException e1) {
				throw e;
			}
		}
		return user;
	}
	public Map<String,Object> getUserMap(){
		Map<String,Object> users = getFileContent("classpath:json/users.json");
		return users;
	}
	public void writeIntoFile(Object object) {
		try {
			File file = ResourceUtils.getFile("classpath:json/users.json");
			String content = JSON.toJSONString(object);
			FileUtils.writeStringToFile(file, content, Charset.forName("UTF-8"));
		} catch (FileNotFoundException e) {
			log.error(e.getMessage(),e);
			throw new UsernameNotFoundException(e.getMessage());
		} catch (IOException e) {
			log.error(e.getMessage(),e);
		}
	};
	private User getUserInFile(String filePath, String username) {
		User user = new User();
		try {
			Map<String,Object> users = getFileContent(filePath);
			if (users.get(username) == null) {
				throw new UsernameNotFoundException("Username "+username+" not found in users.");
			}
			JSONObject right = (JSONObject) users.get(username);
			user = JSONObject.parseObject(right.toJSONString(), User.class);
		} catch (UsernameNotFoundException e) {
			log.error(e.getMessage(),e);
			throw new UsernameNotFoundException(e.getMessage());
		}
		return user;
	}
	private Map<String,Object> getFileContent(String filePath){
		Map<String,Object> users;
		try {
			File file = ResourceUtils.getFile(filePath);
			String content = FileUtils.readFileToString(file);
			users = JSONObject.parseObject(content);
		} catch (FileNotFoundException e) {
			log.error(e.getMessage(),e);
			throw new UsernameNotFoundException(e.getMessage());
		} catch (IOException e) {
			log.error(e.getMessage(),e);
			throw new UsernameNotFoundException(e.getMessage());
		}
		return users;
	}
	public static void main(String[] args) {
		UserService service = new UserService();
		User user = service.getUserByName("admin1");
		log.info(user.toString());
	}

}
